/**
 * 代码生成器类
 * 负责根据配置生成ESP-IDF项目代码
 */

export class CodeGenerator {
    constructor(state) {
        this.state = state;
    }

    /**
     * 生成完整项目
     * @returns {Object} 项目文件对象
     */
    generateProject() {
        const files = {};
        
        // 生成主程序代码
        files['main/main.c'] = this.generateMainCode();
        
        // 生成CMakeLists.txt
        files['CMakeLists.txt'] = this.generateCMakeLists();
        
        // 生成sdkconfig
        files['sdkconfig'] = this.generateSdkConfig();
        
        // 如果启用OTA，生成分区表
        const features = this.state.getFeatures();
        if (features.ota) {
            files['partitions.csv'] = this.generatePartitionTable();
        }
        
        return files;
    }

    /**
     * 生成主程序代码
     * @returns {string} main.c文件内容
     */
    generateMainCode() {
        const chipModel = this.state.getChipModel();
        const projectName = this.state.getProjectName();
        const features = this.state.getFeatures();
        const pinConfigurations = this.state.getPinConfigurations();
        
        let code = `/* ESP32 项目主程序 - ${projectName}
 * 芯片型号: ${chipModel}
 * 生成时间: ${new Date().toLocaleString('zh-CN')}
 */

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
`;

        if (features.wifi) {
            code += `#include "esp_wifi.h"
#include "esp_event.h"
#include "nvs_flash.h"
`;
        }

        if (features.bluetooth) {
            code += `#include "esp_bt.h"
`;
        }

        if (features.httpServer) {
            code += `#include "esp_http_server.h"
`;
        }

        if (features.ota) {
            code += `#include "esp_ota_ops.h"
`;
        }

        // 添加引脚相关的头文件
        if (Object.keys(pinConfigurations).length > 0) {
            code += `#include "driver/gpio.h"
`;
        }

        code += `
void app_main(void)
{
    printf("Hello from ${projectName}!\\n");
    printf("芯片型号: ${chipModel}\\n");
    
`;

        // 添加WiFi初始化代码
        if (features.wifi) {
            code += `    // WiFi初始化代码
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    
    esp_netif_create_default_wifi_sta();
    
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    
    printf("WiFi功能已初始化\\n");
`;
        }

        // 添加蓝牙初始化代码
        if (features.bluetooth) {
            code += `    // 蓝牙初始化代码
    esp_bluedroid_init();
    esp_bluedroid_enable();
    
    printf("蓝牙功能已初始化\\n");
`;
        }

        // 添加HTTP服务器初始化
        if (features.httpServer) {
            code += `    // HTTP服务器初始化
    // TODO: 添加HTTP服务器配置代码
    
    printf("HTTP服务器功能已启用\\n");
`;
        }

        // 添加OTA初始化
        if (features.ota) {
            code += `    // OTA功能初始化
    // TODO: 添加OTA配置代码
    
    printf("OTA更新功能已启用\\n");
`;
        }

        // 添加引脚配置代码
        Object.keys(pinConfigurations).forEach(pin => {
            const config = pinConfigurations[pin];
            code += `    // 配置GPIO${pin}为${config.mode}模式\n`;
            
            if (config.mode === 'output') {
                code += `    gpio_config_t io_conf_${pin};
    io_conf_${pin}.intr_type = GPIO_INTR_DISABLE;
    io_conf_${pin}.mode = GPIO_MODE_OUTPUT;
    io_conf_${pin}.pin_bit_mask = (1ULL << GPIO_NUM_${pin});
    io_conf_${pin}.pull_down_en = 0;
    io_conf_${pin}.pull_up_en = 0;
    gpio_config(&io_conf_${pin});
    
`;
            } else if (config.mode === 'input') {
                code += `    gpio_config_t io_conf_${pin};
    io_conf_${pin}.intr_type = GPIO_INTR_DISABLE;
    io_conf_${pin}.mode = GPIO_MODE_INPUT;
    io_conf_${pin}.pin_bit_mask = (1ULL << GPIO_NUM_${pin});
    io_conf_${pin}.pull_down_en = 0;
    io_conf_${pin}.pull_up_en = 1;
    gpio_config(&io_conf_${pin});
    
`;
            } else if (config.mode === 'pwm') {
                code += `    // TODO: 配置GPIO${pin}为PWM模式
    // 这里需要添加LEDC相关配置
    
`;
            } else if (config.mode === 'adc') {
                code += `    // TODO: 配置GPIO${pin}为ADC模式
    // 这里需要添加ADC相关配置
    
`;
            } else if (config.mode === 'uart') {
                code += `    // TODO: 配置GPIO${pin}为UART模式
    // 这里需要添加UART相关配置
    
`;
            } else if (config.mode === 'i2c') {
                code += `    // TODO: 配置GPIO${pin}为I2C模式
    // 这里需要添加I2C相关配置
    
`;
            } else if (config.mode === 'spi') {
                code += `    // TODO: 配置GPIO${pin}为SPI模式
    // 这里需要添加SPI相关配置
    
`;
            }
        });

        code += `    // 主循环
    while (1) {
        printf("运行中...\\n");
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
`;

        return code;
    }

    /**
     * 生成CMakeLists.txt
     * @returns {string} CMakeLists.txt文件内容
     */
    generateCMakeLists() {
        const projectName = this.state.getProjectName();
        const chipModel = this.state.getChipModel();
        
        return `# 项目级CMakeLists.txt
# 项目名称: ${projectName}
# 芯片型号: ${chipModel}
# 生成时间: ${new Date().toLocaleString('zh-CN')}

cmake_minimum_required(VERSION 3.16)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(${projectName})
`;
    }

    /**
     * 生成sdkconfig
     * @returns {string} sdkconfig文件内容
     */
    generateSdkConfig() {
        const projectName = this.state.getProjectName();
        const chipModel = this.state.getChipModel();
        const features = this.state.getFeatures();
        const pinConfigurations = this.state.getPinConfigurations();
        
        let config = `# SDK配置文件
# 项目名称: ${projectName}
# 芯片型号: ${chipModel}
# 生成时间: ${new Date().toLocaleString('zh-CN')}

CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y
CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ=240
CONFIG_FREERTOS_HZ=100
`;

        if (features.wifi) {
            config += `CONFIG_ESP_WIFI_ENABLED=y
CONFIG_LWIP_DHCP_MAX_NIP=3
`;
        }

        if (features.bluetooth) {
            config += `CONFIG_BT_ENABLED=y
`;
        }

        if (features.httpServer) {
            config += `CONFIG_HTTPD_SERVER_SUPPORT=y
`;
        }

        if (features.ota) {
            config += `CONFIG_OTA_UPDATES_ENABLED=y
CONFIG_OTA_NUM_CUSTOM_PARTS=2
`;
        }

        // 添加引脚配置
        Object.keys(pinConfigurations).forEach(pin => {
            const pinConfig = pinConfigurations[pin];
            if (pinConfig.mode === 'adc') {
                config += `CONFIG_ADC_ENABLED=y
`;
            }
        });

        return config;
    }

    /**
     * 生成分区表
     * @returns {string} partitions.csv文件内容
     */
    generatePartitionTable() {
        const features = this.state.getFeatures();
        if (!features.ota) return null;
        
        return `# ESP-IDF Partition Table
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x6000,
phy_init, data, phy,     0xf000,  0x1000,
factory,  app,  factory, 0x10000, 1M,
ota_0,    app,  ota_0,   ,        1M,
ota_1,    app,  ota_1,   ,        1M,
`;
    }
}